﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaterCloud.Code;
using WaterCloud.DataBase;
using WaterCloud.Domain;
using WaterCloud.Domain.Entity.STZBManage;
using WaterCloud.Domain.Statistics;

namespace WaterCloud.Service.STZBManage
{
    /// <summary>
    /// 藏宝阁链接服务类
    /// </summary>
    public class STZB_CbgUrlService : BaseService<CbgUrl>, IDenpendency
    {
        public STZB_CbgUrlService(ISqlSugarClient context) : base(context)
        {
        }

        /// <summary>
        /// 添加藏宝阁链接
        /// </summary>
        /// <param name="urlStr">链接字符串多个,号隔开</param>
        public async Task Add_CbgUrl(string urlStr)
        {
            string[] urlArr = urlStr.Trim().Split(',');
            //获取已有的链接
            var existUrls = await repository.IQueryable().Where(x => urlArr.Contains(x.Url)).Select(x => x.Url).ToListAsync();
            //排除已有的链接
            urlArr = urlArr.Except(existUrls).ToArray();
            //遍历添加
            foreach (string url in urlArr)
            {
                CbgUrl cbgUrl = new CbgUrl
                {
                    Url = url,
                    Open_State = 0,
                    Crawl_Time = null,
                    CreateTime = DateTime.UtcNow.AddHours(8)
                };
                await repository.Insert(cbgUrl);
            }
        }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="cbgUrl"></param>
        /// <returns></returns>
        public async Task AddOrEdit(CbgUrl cbgUrl)
        {
            if (cbgUrl.Id > 0) //修改
            {
                var data = await repository.IQueryable().Where(x => x.Id == cbgUrl.Id).FirstAsync();
                data.Url = cbgUrl.Url;
                data.Open_State = cbgUrl.Open_State;
                await repository.Update(data);
            }
            else
            {
                cbgUrl.Crawl_Time = null;
                cbgUrl.CreateTime = DateTime.UtcNow.AddHours(8);
                await repository.Insert(cbgUrl);
            }
        }

        /// <summary>
        /// 修改点击状态和爬取时间
        /// </summary>
        /// <param name="url">链接数组</param>
        /// <returns></returns>
        public async Task Update_CbgUrl(string[] url)
        {
            //获取数据
            var data = await repository.IQueryable().Where(x => url.Contains(x.Url)).ToListAsync();
            if (data.Count > 0) //有数据
            {
                data.ForEach(x => { x.Open_State = 1; x.Crawl_Time = DateTime.Now.AddHours(8); });
                await repository.Db_Context().Updateable<CbgUrl>(data).ExecuteCommandAsync();
            }
        }

        /// <summary>
        /// 获取今日未点击的藏宝阁链接
        /// </summary>
        /// <returns></returns>
        public async Task<SqlSugarDataResult<CbgUrl>> GetCbgUrl()
        {
            //获取今天的日期
            DateTime time = DateTime.Now;
            var data = await repository.IQueryable()
                .Where(x => (x.Open_State == 0 || x.Crawl_Time == null) && SqlFunc.DateDiff(DateType.Day, x.CreateTime, time) == 0) //未点击且爬取时间为空且今日数据
                .OrderBy(x => x.CreateTime) //按创建时间升序
                .ToListAsync();
            return new SqlSugarDataResult<CbgUrl> { List = data, Total = data.Count };
        }


        /// <summary>
        /// 获取藏宝阁链接列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="keyword">关键词</param>
        /// <param name="open_State">点开状态 0:未点开、1:点开</param>
        /// <returns></returns>
        public async Task<List<CbgUrl>> Get_CBGUrl_GridJson(SoulPage<CbgUrl> pagination, string keyword, int open_State)
        {
            open_State = open_State - 2;
            var data = repository.IQueryable()
                .WhereIF(!string.IsNullOrEmpty(keyword), x => x.Url.Contains(keyword))
                .WhereIF(open_State >= 0, x => x.Open_State == open_State);
            //权限过滤（保证分页参数存在）
            data = GetDataPrivilege("x", "", data);
            return await data.ToPageListAsync(pagination);
        }


        /// <summary>
        /// 删除藏宝阁链接数据
        /// </summary>
        /// <param name="ids">数据id，多个值用逗号隔开</param>
        /// <returns></returns>
        public async Task Delete_CBGUrl(string ids)
        {
            var idArr = ids.Split(',');
            await repository.Delete(x => idArr.Contains(x.Id.ToString()));
        }

        public async Task<CbgUrl> GetFormJson(int id)
        {
            var data = await repository.IQueryable().Where(x => x.Id == id).FirstAsync();
            return data;
        }

        /// <summary>
        /// 获取今日爬取数量、总待爬取数量
        /// </summary>
        /// <returns></returns>
        public async Task<CrawlNum> GetDayCrawlNum()
        {
            // 今天最早时间（00:00:00）
            DateTime todayStart = DateTime.Today;
            // 今天最晚时间（23:59:59.999）
            DateTime todayEnd = DateTime.Today.AddDays(1).AddTicks(-1);
            CrawlNum result = new CrawlNum();
            //获取今天爬取数量
            result.ToDay_Num = await repository.IQueryable().Where(x => x.Crawl_Time >= todayStart && x.Crawl_Time <= todayEnd && x.Open_State == 1).CountAsync();
            //获取总待爬取数量
            result.Total = await repository.IQueryable().Where(x => x.Open_State == 0).CountAsync();
            return result;
        }
    }
}
